package com.da.lon.wang.xlg.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.da.lon.wang.xlg.MyApplication;
import com.da.lon.wang.xlg.R;
import com.da.lon.wang.xlg.adapter.SearchHistoryAdapter;
import com.da.lon.wang.xlg.bean.HotSearchBean;
import com.da.lon.wang.xlg.bean.SearchData;
import com.da.lon.wang.xlg.constants.PreferencesConfig;
import com.da.lon.wang.xlg.constants.XLGConstants;
import com.da.lon.wang.xlg.http.HttpLoader;
import com.da.lon.wang.xlg.http.HttpLoader.OnWebLoadListener;
import com.da.lon.wang.xlg.util.DateUtils;
import com.da.lon.wang.xlg.util.PreferenceUtils;
import com.da.lon.wang.xlg.util.XLGDataUtils;
import com.da.lon.wang.xlg.view.HistoryListView;
import com.da.lon.wang.xlg.view.WordWrapView;
import com.umeng.analytics.MobclickAgent;

import net.tsz.afinal.http.AjaxParams;

import java.util.ArrayList;
import java.util.List;


public class HotSearchActivity extends BaseActivity implements OnClickListener {

    private static final String SEARCH_HISTORY = "search_history";
    private TextView tvSearch;
    private ImageView ivDeleteSearch;
    private EditText etSearch;
    private TextView tvHistory;
    private HistoryListView lvHistory;
    private Button btnClearHistory;
    private LinearLayout lyHistory;
    private ImageButton leftButton;
    private SharedPreferences sp;
    private List<SearchData> lstHistory;
    private List<SearchData> lstAllHistory;
    private SearchHistoryAdapter mAdapter;

    private WordWrapView wordWrapView;
    private HttpLoader<HotSearchBean> loader;
    private Context context;

    private String searchContent;
    private TextView hot_serach_tv;

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
//		MyApplication.showInputWindow(etSearch, this);
        MyApplication.showinputwindow(etSearch, this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ocoffee_hot_search);
        context = this;
        initView();
        initData();
        setListener();
    }

    private void setListener() {
        ivDeleteSearch.setOnClickListener(this);
        tvSearch.setOnClickListener(this);
        btnClearHistory.setOnClickListener(this);

        leftButton.setOnClickListener(this);

        lvHistory.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View view,
                                    int position, long arg3) {
                if (position > 0) {
                    SearchData data = (SearchData) mAdapter
                            .getItem(position - 1);
                    etSearch.setText(data.getContent());
                    tvSearch.performClick();
                }
            }
        });

        lvHistory.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {
                MyApplication.hideInputWindow(etSearch, HotSearchActivity.this);
                return false;
            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                performFiltering(s);
                if (s.length() > 0) {
                    ivDeleteSearch.setVisibility(View.VISIBLE);
                    tvSearch.setText("搜索");
                    tvHistory.setText("猜你想搜");
                } else {
                    ivDeleteSearch.setVisibility(View.INVISIBLE);
                    tvSearch.setText("取消");
                    tvHistory.setText("历史记录");
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }


    public void performFiltering(CharSequence inputContent) {
        if (lstHistory.size() > 0) {
            lstHistory.clear();
        }
        lstHistory.addAll(lstAllHistory);
        mAdapter.notifyDataSetChanged();
        if (lstHistory.size() < 1) {
            btnClearHistory.setVisibility(View.GONE);
        } else {
            btnClearHistory.setVisibility(View.VISIBLE);
        }
    }

    private void initData() {
        sp = getSharedPreferences(SEARCH_HISTORY, 0);
        lstAllHistory = new ArrayList<>();
        lstHistory = new ArrayList<>();
        readSearchHistory();
        lstHistory.addAll(lstAllHistory);
        mAdapter = new SearchHistoryAdapter(this, lstHistory);
        lvHistory.setAdapter(mAdapter);
        if (lstHistory != null && lstHistory.size() < 1) {
            // lvHistory.setVisibility(View.GONE);
            btnClearHistory.setVisibility(View.GONE);
            lyHistory.setVisibility(View.GONE);
        }
    }

    private void readSearchHistory() {
        if (lstAllHistory.size() > 0) {
            lstAllHistory.clear();
        }
        String longhistory = sp.getString(SEARCH_HISTORY, "");
        if (TextUtils.isEmpty(longhistory)) {
            return;
        }
        String[] hisArrays = longhistory.split(",");
        for (int i = 0; hisArrays != null && i < hisArrays.length; i++) {
            lstAllHistory.add(new SearchData().setContent(hisArrays[i]));
        }


    }

    private void initView() {
        tvSearch = (TextView) findViewById(R.id.tv_search);
        ivDeleteSearch = (ImageView) findViewById(R.id.iv_delete_search);
        etSearch = (EditText) findViewById(R.id.et_search);
        lvHistory = (HistoryListView) findViewById(R.id.lv_history);
        leftButton = (ImageButton) findViewById(R.id.hotsearch_left);

        View header = LayoutInflater.from(context).inflate(
                R.layout.hot_ser_item, null);
        tvHistory = (TextView) header.findViewById(R.id.tv_history);
        wordWrapView = (WordWrapView) header
                .findViewById(R.id.hotsearch_wordwrap);
        hot_serach_tv = (TextView) header.findViewById(R.id.hot_serach_tv);
        lyHistory = (LinearLayout) header.findViewById(R.id.ly_history);
        btnClearHistory = (Button) header.findViewById(R.id.btn_clear_history);
        lvHistory.addHeaderView(header);

        loader = new HttpLoader<>(context, XLGConstants.URL
                + "/Search-hot", HotSearchBean.class, 10 * 1000);

        AjaxParams params = new AjaxParams();
        params.put("token", XLGDataUtils.encrypt2MD5("Search" + "2015#$%"
                + "hot"));
        params.put("version", "21");

        loader.setManagerListener(new OnWebLoadListener<HotSearchBean>() {

            @Override
            public void OnStart() {
                showDialog();
            }

            @Override
            public void OnError(String error) {
                dismissDialog();
            }

            @Override
            public void onSuccess(HotSearchBean t) {
                dismissDialog();

                if (t != null && t.getCode().equals("000000")) {
                    for (int i = 0; i < t.getResult().size(); i++) {
                        final TextView textView = new TextView(context);
                        textView.setText(t.getResult().get(i).getValue());
                        textView.setGravity(Gravity.CENTER);
                        textView.setTag(i);
                        if (t.getResult().get((Integer) textView.getTag())
                                .getIsred().equals("1")) {
                            textView.setBackgroundResource(R.drawable.ocoffee_hotsearch_red);
                        } else {
                            textView.setBackgroundResource(R.drawable.ocoffee_hotsearch_normal);
                        }

                        textView.setOnClickListener(new OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                searchContent = textView.getText().toString();

                                Intent intent = new Intent(
                                        HotSearchActivity.this,
                                        ResultSearchActivity.class);
                                intent.putExtra("searchContent", searchContent);
                                startActivity(intent);
                            }
                        });

                        wordWrapView.addView(textView);
                    }

                } else {
                    hot_serach_tv.setVisibility(View.GONE);
                }

            }
        });
        loader.loadData(params);


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.hotsearch_left:
                MyApplication.hideInputWindow(etSearch, HotSearchActivity.this);
                finish();
                break;

            case R.id.iv_delete_search:
                etSearch.setText("");
                ivDeleteSearch.setVisibility(View.INVISIBLE);
                break;
            case R.id.tv_search:


                PreferenceUtils.getInstance().SetSettingString(
                        PreferencesConfig.SEARCH_SATTR, "");
                MyApplication.getInstance().setPrice_hight("");
                MyApplication.getInstance().setPrice_small("");

                searchContent = etSearch.getText().toString().trim();
                if (TextUtils.isEmpty(searchContent)) {
                    MyApplication.hideInputWindow(etSearch, HotSearchActivity.this);
                    HotSearchActivity.this.finish();
                } else {
//					saveSearchHistory(searchContent);
                    DateUtils.saveSearchHistory(searchContent, context);
                    readSearchHistory();
                    if (lstHistory != null && lstHistory.size() > 0) {
                        lstHistory.clear();
                    }
                    lstHistory.addAll(lstAllHistory);
                    mAdapter.notifyDataSetChanged();
                    // lvHistory.setVisibility(View.VISIBLE);
                    btnClearHistory.setVisibility(View.VISIBLE);
                    lyHistory.setVisibility(View.VISIBLE);

                    Intent intent = new Intent(HotSearchActivity.this,
                            ResultSearchActivity.class);
                    intent.putExtra("searchContent", searchContent);
                    startActivity(intent);
                }


                break;
            case R.id.btn_clear_history:// 清除历史记录
                clearAllSearchHistory();
                readSearchHistory();
                if (lstHistory != null && lstHistory.size() > 0) {
                    lstHistory.clear();
                }
                lstHistory.addAll(lstAllHistory);
                mAdapter.notifyDataSetChanged();
                // lvHistory.setVisibility(View.GONE);
                btnClearHistory.setVisibility(View.GONE);
                lyHistory.setVisibility(View.GONE);
                Toast.makeText(HotSearchActivity.this, "清空历史记录成功",
                        Toast.LENGTH_SHORT).show();
                break;

            default:
                break;
        }
    }


    private void clearAllSearchHistory() {
        Editor editor = sp.edit();
        editor.clear();
        editor.commit();
    }
}
